package org.jeecg.jt808.req;

import io.netty.buffer.ByteBuf;
import lombok.Data;
import org.jeecg.jt808.vo.JT808DataPacket;

@Data
public class TerminalAttributeResponseMsg extends JT808DataPacket {

    private int terminalType; // 终端类型
    private String manufacturerId; // 制造商 ID
    private String terminalModel; // 终端型号
    private String terminalId; // 终端 ID
    private String simIccid; // SIM 卡 ICCID
    private int hardwareVersionLength; // 硬件版本号长度
    private String hardwareVersion; // 硬件版本号
    private int firmwareVersionLength; // 固件版本号长度
    private String firmwareVersion; // 固件版本号
    private int gnssModuleAttributes; // GNSS 模块属性
    private int communicationModuleAttributes; // 通信模块属性

    public TerminalAttributeResponseMsg(ByteBuf byteBuf) {
        super(byteBuf);
    }

    @Override
    public void parseBody() {
        ByteBuf bb = this.payload;

        // 解析终端类型
        this.setTerminalType(bb.readUnsignedShort());

        // 解析制造商 ID
        byte[] manufacturerIdBytes = new byte[5];
        bb.readBytes(manufacturerIdBytes);
        this.setManufacturerId(new String(manufacturerIdBytes));

        // 解析终端型号
        byte[] terminalModelBytes = new byte[20];
        bb.readBytes(terminalModelBytes);
        this.setTerminalModel(new String(terminalModelBytes).trim());

        // 解析终端 ID
        byte[] terminalIdBytes = new byte[7];
        bb.readBytes(terminalIdBytes);
        this.setTerminalId(new String(terminalIdBytes).trim());

        // 解析 SIM 卡 ICCID
        byte[] simIccidBytes = new byte[10];
        bb.readBytes(simIccidBytes);
        this.setSimIccid(bytesToBcdString(simIccidBytes)); // 转换为 BCD 字符串

        // 解析硬件版本号长度
        this.setHardwareVersionLength(bb.readUnsignedByte());

        // 解析硬件版本号
        byte[] hardwareVersionBytes = new byte[this.hardwareVersionLength];
        bb.readBytes(hardwareVersionBytes);
        this.setHardwareVersion(new String(hardwareVersionBytes).trim());

        // 解析固件版本号长度
        this.setFirmwareVersionLength(bb.readUnsignedByte());

        // 解析固件版本号
        byte[] firmwareVersionBytes = new byte[this.firmwareVersionLength];
        bb.readBytes(firmwareVersionBytes);
        this.setFirmwareVersion(new String(firmwareVersionBytes).trim());

        // 解析 GNSS 模块属性
        this.setGnssModuleAttributes(bb.readUnsignedByte());

        // 解析通信模块属性
        this.setCommunicationModuleAttributes(bb.readUnsignedByte());
    }

    private String bytesToBcdString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X", b));
        }
        return sb.toString();
    }
}